var pathRequestUrl;
var page_size = 20;
var composerRecord;
var composerObj;
var gridComposer;
var row_current = -1;
var col_current = -1;
var date_format_string = 'd/m/Y';
var date_sql_format_string = 'Y-m-d';

Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field){
        var date = field.parseDate(val);
        
        if (!date) {
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        }
        else 
            if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
                var end = Ext.getCmp(field.endDateField);
                end.setMinValue(date);
                end.validate();
                this.dateRangeMin = date;
            }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

Ext.onReady(function(){
    Ext.QuickTips.init();
    pathRequestUrl = 'ListComposerData.php';
    
    var formatDate = function(value){
        if (isEmpty(value)) 
            return '';
        try {
            return value ? ((value.dateFormat('d/m/Y') != '01/01/1900') ? value.dateFormat('d/m/Y') : '') : '';
        } 
        catch (e) {
            console.debug(e);
        }
    };
    //--------------------------	
    Ext.ns('Extensive.grid');
    Extensive.grid.ItemDeleter = Ext.extend(Ext.grid.RowSelectionModel, {
        width: 30,
        sortable: false,
        dataIndex: 0, // this is needed, otherwise there will be an error		
        menuDisabled: true,
        fixed: true,
        id: 'deleter',
        initEvents: function(){
            Extensive.grid.ItemDeleter.superclass.initEvents.call(this);
            this.grid.on('cellclick', function(grid, rowIndex, columnIndex, e){
                //if(rowIndex == 0) return;
                if (columnIndex == grid.getColumnModel().getIndexById('deleter')) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (record.data.object_id == 0) 
                        return false;
                    Ext.Msg.show({
                        title: 'Xác nhận',
                        buttons: Ext.MessageBox.YESNO,
                        icon: Ext.MessageBox.QUESTION,
                        msg: "Bạn có chắc là muốn xóa Nhạc Sĩ <b>" + record.data.object_name + "</b> không ?",
                        fn: function(btn){
                            if (btn == 'yes') {
                                deleteComposer(record);
                            }
                        }
                    });
                    
                    /*var record = grid.getStore().getAt(rowIndex);
                     grid.getStore().remove(record);
                     grid.getView().refresh();*/
                }
            });
        },
        renderer: function(v, p, record, rowIndex){
            //if(rowIndex > 0)
            return '<div class="extensive-remove" style="width: 15px; height: 16px;"></div>';
        }
    });
    var itemDeleter = new Extensive.grid.ItemDeleter();
    
    //Render Tooltip	
    var render_composer_name = function(v, p){
        //v : value , p : cell
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="Nhạc Sĩ<hr />"';
        p.attr += 'ext:qtip="' + v + '<br/>&nbsp;"';
        return v;
    };
    
    var render_composer_company = function(v, p){
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="Công Ty<hr />"';
        p.attr += 'ext:qtip="' + v + '<br/>&nbsp;"';
        return v;
    };
    
    var render_composer_address = function(v, p){
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="Địa Chỉ<hr />"';
        p.attr += 'ext:qtip="' + v + '<br/>&nbsp;"';
        return v;
    };
    
    
    //-----------------------------
    composerRecord = [{
        name: 'object_id',
        type: 'string'
    }, {
        name: 'object_number',
        type: 'string'
    }, {
        name: 'object_name',
        type: 'string'
    }, {
        name: 'object_company',
        type: 'string'
    }, {
        name: 'object_address',
        type: 'string'
    }, {
        name: 'object_phone',
        type: 'string'
    }, {
        name: 'object_mobile',
        type: 'string'
    }, {
        name: 'object_email',
        type: 'string'
    }/*, {
        name: 'object_fax',
        type: 'string'
    }*/, {
        name: 'object_type',
        type: 'string'
    }/*, {
        name: 'created_date',
        type: 'date'
    }*/, {
        name: 'contract_id',
        type: 'string'
    }, {
        name: 'contract_number',
        type: 'string'
    }, {
        name: 'contract_date',
        type: 'date'
    }, {
        name: 'contract_end',
        type: 'date'
    }];
    
    composerObj = Ext.data.Record.create(composerRecord);
    
    var composer = {
        add: function(){
    		addNewComposer(storeComposer.getCount(), 2, true);
    		/*
    		if(storeComposer.getCount() < storeComposer.getTotalCount()) {
    			bbarComposer.moveLast();
    			//add new row
    			addNewComposer(storeComposer.getCount(), 3, true);
    		}else{
    			//add new row
    			addNewComposer(storeComposer.getCount(), 3, true);
    		};*/
        },
        remove: function(){
        },
        find: function(){
            gridComposer.getStore().load();
        },
        print: function(){
			var action = 'export';
        	var srch_object_number = Ext.getCmp('srch_object_number').getValue();
            var srch_object_name = Ext.getCmp('srch_object_name').getValue();
            var srch_object_company = Ext.getCmp('srch_object_company').getValue();
            var srch_object_address = Ext.getCmp('srch_object_address').getValue();
            var srch_object_type = Ext.getCmp('srch_object_type').getValue();			
    		var srch_contract_number = Ext.getCmp('srch_contract_number').getValue();
    		var srch_from_contract_date = isEmpty(Ext.getCmp('srch_from_contract_date').getValue())?'':Ext.getCmp('srch_from_contract_date').getValue().dateFormat(date_sql_format_string);
    		var srch_to_contract_date = isEmpty(Ext.getCmp('srch_to_contract_date').getValue())?'':Ext.getCmp('srch_to_contract_date').getValue().dateFormat(date_sql_format_string);
    		var srch_check_contract = Ext.getCmp('srch_check_contract').getValue();
			window.open(
					pathRequestUrl + '?action=' + action + 
					'&ob=' + srch_object_number +
					'&on' + srch_object_name +
					'&oc=' + srch_object_company +
					'&oa=' + srch_object_address +
					'&ot=' + srch_object_type +
					'&cn=' + srch_contract_number +
					'&fcd=' + srch_from_contract_date +
					'&tcd=' + srch_to_contract_date +
					'&cc=' + srch_check_contract 					
			, null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
        }
    };
    
    var storeComposer = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id'
        }, composerObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeComposer.on('beforeload', function(){
        storeComposer.baseParams.action = 'get';
        storeComposer.baseParams.start = 0;
        storeComposer.baseParams.limit = page_size;
        storeComposer.baseParams.srch_object_number = Ext.getCmp('srch_object_number').getValue();
        storeComposer.baseParams.srch_object_name = Ext.getCmp('srch_object_name').getValue();
        storeComposer.baseParams.srch_object_company = Ext.getCmp('srch_object_company').getValue();
        storeComposer.baseParams.srch_object_address = Ext.getCmp('srch_object_address').getValue();
        storeComposer.baseParams.srch_object_type = Ext.getCmp('srch_object_type').getValue();			
		storeComposer.baseParams.srch_contract_number = Ext.getCmp('srch_contract_number').getValue();
		storeComposer.baseParams.srch_from_contract_date = isEmpty(Ext.getCmp('srch_from_contract_date').getValue())?'':Ext.getCmp('srch_from_contract_date').getValue().dateFormat(date_sql_format_string);
		storeComposer.baseParams.srch_to_contract_date = isEmpty(Ext.getCmp('srch_to_contract_date').getValue())?'':Ext.getCmp('srch_to_contract_date').getValue().dateFormat(date_sql_format_string);
		storeComposer.baseParams.srch_check_contract = Ext.getCmp('srch_check_contract').getValue();
    });
	
    //Type Vote for search:----------------------------------------------
    var typeObject = new Ext.data.SimpleStore({
        data: [[2, 'Nhạc sĩ'], [3, 'Nhạc/Ca sĩ']],
        fields: ['object_type', 'type_name']
    });
    
    var render_object_type = function(val){
        try {
            if (val == null || val == '') 
                return '';
            return typeObject.queryBy(function(rec){
                return rec.data.object_type == val;
            }).itemAt(0).data.type_name;
        } 
        catch (e) {
        }
    }
	
	//Type Vote for search:----------------------------------------------
    var storeCheckContract = new Ext.data.SimpleStore({
        data: [[1, 'Có hợp đồng'], [2, 'Chưa có hợp đồng'], [3, 'Tất cả']],
        fields: ['composer_contract_id', 'composer_contract_name']
    });
    
    var render_composer_contract = function(val){
        try {
            if (val == null || val == '') 
                return '';
            return storeCheckContract.queryBy(function(rec){
                return rec.data.composer_contract_id == val;
            }).itemAt(0).data.composer_contract_name;
        } 
        catch (e) {
        }
    }
	
	
    
    var tbarObject = new Ext.Panel({
        items: [{
            xtype: 'toolbar',
            id: 'tbar1',
            items: [{
                xtype: 'tbtext',
                width: 75,
                text: 'Nhạc Sĩ: '
            }, {
                xtype: 'tbtext',
                width: 25,
				align: 'right',
                text: 'Mã: '
            }, {
                xtype: 'textfield',
                id: 'srch_object_number',
                width: 80,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 27,
                text: 'Tên: ',
            }, {
                xtype: 'textfield',
                id: 'srch_object_name',
                width: 100,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 25,
                text: 'C.ty: ',
            }, {
                xtype: 'textfield',
                id: 'srch_object_company',
                width: 150,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 33,
                text: 'Đ.Chỉ: ',
            }, {
                xtype: 'textfield',
                id: 'srch_object_address',
                width: 150,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }, '-', {
				xtype: 'tbtext',
                width: 30,
                text: 'Vị trí: ',
            }, new Ext.form.ComboBox({
                id: 'srch_object_type',
                typeAhead: true,
                store: typeObject,
                valueField: 'object_type',
                displayField: 'type_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                allowBlank: true,
                editable: true,
                width: 105,
                minChars: 1,
                lazyRender: true,
                selectOnFocus: true,
                listeners: {
                    select: function(combo, record, index){
                       
                    },
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            })]
        }, {
            xtype: 'toolbar',
            id: 'tbar2',
            items: [{
                xtype: 'tbtext',
                width: 75,
                text: 'HỢP ĐỒNG: ',
            }, {
                xtype: 'tbtext',
                width: 25,
                text: 'Số: '
            }, {
                xtype: 'textfield',
                id: 'srch_contract_number',
                width: 80,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 47,
                text: 'Từ ngày: ',
            }, {
				xtype: 'datefield',
                width: 80,
                id: 'srch_from_contract_date',
                format: date_format_string,
                selectOnFocus: true,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
			}, '-', {
                xtype: 'tbtext',
                width: 55,
                text: 'Đến ngày: ',
            }, {
				xtype: 'datefield',
                width: 80,
                id: 'srch_to_contract_date',
                format: date_format_string,
                selectOnFocus: true,
                listeners: {
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
			}, '-', {
                xtype: 'tbtext',
                width: 27,
                text: 'Loại:',
            }, new Ext.form.ComboBox({
                id: 'srch_check_contract',
                typeAhead: true,
                store: storeCheckContract,
                valueField: 'composer_contract_id',
                displayField: 'composer_contract_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                allowBlank: true,
                editable: true,
                width: 100,
                minChars: 1,
                lazyRender: true,
                selectOnFocus: true,
                listeners: {
                    select: function(combo, record, index){
                        
                    },
                    change: function(e){
            			gridComposer.getStore().load();
                    }
                }
            }), '-', {
                text: 'Tìm Kiếm',
                id: 'find_composer_action',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/find.png',
                style: 'padding-left: 5px;',
                handler: composer.find
            }, '->', {
                text: 'Thêm',
                id: 'add_composer',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/add.png',
                handler: composer.add
            }, '-', {
                text: 'In',
                id: 'printer_add',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/printer.png',
                handler: composer.print
            }]
        }]
    });
    
    var cmbPerPage = new Ext.form.ComboBox({
        name: 'perpage',
        width: 80,
        store: new Ext.data.SimpleStore({
            data: [[20, '20'], [50, '50'], [100, '100'], [300, '300'], [500, '500'], [1000, '1000']],
            id: 0,
            fields: ['id', 'value']
        }),
        mode: 'local',
        value: '20',
        listWidth: 80,
        triggerAction: 'all',
        displayField: 'value',
        valueField: 'value',
        editable: false,
        forceSelection: true
    });
    
    cmbPerPage.on('select', function(combo, record){
        bbarComposer.pageSize = parseInt(record.get('id'), 10);
        bbarComposer.doLoad(bbarComposer.cursor);
    }, this);
    
    var bbarComposer = new Ext.PagingToolbar({
        store: storeComposer, // the store you use in your grid
        displayInfo: true,
        pageSize: page_size,
        id: 'bbar_object',
        items: ['-', 'Số tin', cmbPerPage],
        listeners: {
            change: function(tb, data){
                /*if (data.activePage == data.pages) {
                    if (gridComposer.getStore().getCount() > 0) {
                        addNewComposer(gridComposer.getStore().getCount(), 3, true);
                    }else{
                    	addNewComposer(0, 3, true);
                    }
                }*/
            }
        }
    });
    
    var cmObject = new Ext.grid.ColumnModel({
        defaults: {
            sortable: true
        },
        columns: [new Ext.grid.RowNumberer(), itemDeleter, {
            header: 'Mã Nhạc Sĩ',
            dataIndex: 'object_number',
            width: 50,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Tên Nhạc Sĩ',
            dataIndex: 'object_name',
            width: 100,
            renderer: render_composer_name,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Vị Trí',
            id: 'object_type',
            width: 60,
            dataIndex: 'object_type',
            editable: true,
            renderer: render_object_type,
            editor: new Ext.form.ComboBox({
                typeAhead: true,
                store: typeObject,
                valueField: 'object_type',
                displayField: 'type_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                allowBlank: true,
                editable: true,
                width: 80,
                //minListWidth: 100,
                //itemSelector: 'div.search-item',
                minChars: 1,
                //listWidth: 380,
                lazyRender: true,
                selectOnFocus: true,
                listeners: {
                    select: function(combo, record, index){
                        gridComposer.startEditing(row_current, col_current);
                    }
                }
            })
        }, {
			header: 'Số HĐ',
            dataIndex: 'contract_number',
            width: 130,
			editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
		}, {
			header: 'Ngày HĐ',
            dataIndex: 'contract_date',
            width: 70,
            renderer: formatDate,
			editor: new Ext.form.DateField({
				allowBlank: true,
				selectOnFocus: true,
				format: date_format_string
			})
		}, {
			header: 'Ngày kết thúc',
            dataIndex: 'contract_end',
            width: 70,
            renderer: formatDate,
			editor: new Ext.form.DateField({
				allowBlank: true,
				selectOnFocus: true,
				format: date_format_string
			})
		}, {
            header: 'Công Ty',
            dataIndex: 'object_company',
            width: 100,
            renderer: render_composer_company,
            editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Địa Chỉ',
            dataIndex: 'object_address',
            width: 100,
            renderer: render_composer_address,
            editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Điện Thoại',
            dataIndex: 'object_phone',
            width: 70,
            editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
						if(!forceNumber(e)) e.stopEvent();
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Di động',
            dataIndex: 'object_mobile',
            width: 70,
            editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
						if(!forceNumber(e)) e.stopEvent();
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Email',
            dataIndex: 'object_email',
            width: 70,
            editor: new Ext.form.TextField({
                allowBlank: true,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }
        /*, {
            header: 'Ngày Tạo',
            dataIndex: 'created_date',
            width: 100,
            renderer: formatDate
        }*/]
    });
    gridComposer = new Ext.grid.EditorGridPanel({
        title: '',
        id: 'gridComposer',
        store: storeComposer,
        cm: cmObject,
        tbar: tbarObject,
        bbar: bbarComposer,
        stripeRows: true,
        height: 600,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
        selModel: itemDeleter,
        viewConfig: {
            forceFit: false,
            deferEmptyText: true,
            emptyText: 'No records found'
        },
        //autoHeight: true,
        listeners: {
            beforeedit: function(e){
                row_current = e.row;
                col_current = e.column;
            },
            afteredit: function(e){
                if (0 == e.record.data.object_id) {
                    insertComposer(e);
                }
                else {
                	if(e.field == 'contract_number' || e.field == 'contract_date' || e.field == 'contract_end') {
                		saveContract(e);
                	}else{
                		updateComposer(e);
                	}
                }
            }
            
        }
    });
    
    var composerFormPanel = new Ext.FormPanel({
        id: 'list_composer_panel',
        iconCls: 'form-icon',
        title: 'Quản lí thông tin Nhạc Sĩ',
        frame: true,
        width: 900,
        renderTo: 'list_composer',
        items: [gridComposer]
    });
    
});

/**
 * Functions --------------------------------------------------------------------------------------
 * Add new row
 * @author huudatxm
 */
var addNewComposer = function(row_insert, col_edit, has_edit){
    var newRecord = new composerObj({
        object_id: 0,
        object_number: null,
        object_name: null,
        object_company: null,
        object_address: null,
        object_phone: null,
        object_mobile: null,
        object_email: null,
        //object_fax: null,
        object_type: 2,
        /*created_date: new Date()*/
		contract_id: null,
		contract_number: null,
		contract_date: null,
		contract_end: null
    });
    gridComposer.getStore().insert(row_insert, newRecord);
    gridComposer.getView().refresh();
    if (has_edit) 
        gridComposer.startEditing(row_insert, col_edit);
    //gridComposer.getStore().insert(gridComposer.getStore().getCount(), newRecord);
}

/**
 * Insert an object
 * @author huudatxm
 */
var insertComposer = function(e){
    if (!checkDataInsert(e)) 
        return;
		
	var contract_date = e.record.data.contract_date ? e.record.data.contract_date.dateFormat(date_sql_format_string) : '';
	var contract_end = e.record.data.contract_end ? e.record.data.contract_end.dateFormat(date_sql_format_string) : '';
			
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
            		alert("Mã "+e.record.data.object_number+" đã tồn tại. Vui lòng chọn mã khác !.");
            		return;
            	}
                e.record.data.object_id = result.data.object_id;
				e.record.data.contract_id = result.data.contract_id;
                e.record.commit();
                /*
                addNewComposer(gridComposer.getStore().getCount(), 3, false);
                gridComposer.startEditing(row_current, col_current);
                */
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'insert',
            object_number: e.record.data.object_number,
            object_name: e.record.data.object_name,
            object_company: e.record.data.object_company,
            object_address: e.record.data.object_address,
            object_phone: e.record.data.object_phone,
            object_mobile: e.record.data.object_mobile,
            object_email: e.record.data.object_email,
            //object_fax: e.record.data.object_fax,
            object_type: e.record.data.object_type,
			contract_number: e.record.data.contract_number,
			contract_date: contract_date,
			contract_end: contract_end
        }
    });
};

/**
 * Check data for insert
 * @author huudatxm
 */
var checkDataInsert = function(e){
	if(!isEmpty(e.record.data.object_email) && !emailChecker(e.record.data.object_email)) {
		alert('Email không hợp lệ !.');
		return false;
	};
    var data = e.record.data;
    return !(isEmpty(data.object_number) || isEmpty(data.object_name));
};

/**
 * Update
 * @author huudatxm
 */
var updateComposer = function(e){
	if(!checkDataInsert(e)) return;
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
            		alert('Mã nhạc sĩ này đã tồn tại. Vui lòng chọn mã khác !.');
            		return;
            	}
                e.record.commit();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
        	action: 'update',
            field: e.field,
            value: e.value,
            object_id: e.record.data.object_id,
            contract_id: e.record.data.contract_id
        }
    });
};

/**
 * Key Control
 * @author datnh
 */
var keyCustom = function(e){
    if (e.keyCode == 40) {
        //KeyDown	
        var store_size = gridComposer.getStore().getCount();
        if ((store_size - 1) == row_current) {
            if (0 == gridComposer.getStore().getAt(store_size - 1).data.object_id) 
                return false;
            addNewComposer(store_size, 2, false);
        }
        row_current++;
        gridComposer.startEditing(row_current, col_current);
        gridComposer.getSelectionModel().selectRow(row_current);
    }
    else 
        if (e.keyCode == 38) {
            //KeyUp
            if (row_current > 0) {
                row_current--;
                gridComposer.startEditing(row_current, col_current);
                gridComposer.getSelectionModel().selectRow(row_current);
            }
        }
};

/**
 * Delete
 * @author huudatxm
 */
var deleteComposer = function(record){
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                gridComposer.getStore().remove(record);
                gridComposer.getView().refresh();
            }
            else {
                alert('Không thể xóa vì lỗi phát sinh.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'delete',
            object_id: record.data.object_id
        }
    });
};

/**
 * Save contract
 * @author huudatxm
 */
var saveContract = function(e){
	if(isEmpty(e.record.data.object_id)||e.record.data.object_id==0) return;
	var act = 'updateContract';
	if(isEmpty(e.record.data.contract_id)||e.record.data.contract_id==0) {
		if(isEmpty(e.record.data.contract_number)) return;
		act = 'insertContract';
	}

	var contract_date = e.record.data.contract_date ? e.record.data.contract_date.dateFormat(date_sql_format_string) : '';
	var contract_end = e.record.data.contract_end ? e.record.data.contract_end.dateFormat(date_sql_format_string) : '';
	var field = e.field;
    var value = e.value;
	if(field == 'contract_date' || field == 'contract_end') {
		value = value ? value.dateFormat(date_sql_format_string) : '';
	};
	
	Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(act == 'insertContract') {
            		e.record.data.contract_id = result.data.contract_id;
            	}
                e.record.commit();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: act,       
            field: field,
            value: value,
            object_id: e.record.data.object_id,
            contract_id: e.record.data.contract_id,
            contract_number: e.record.data.contract_number,
            contract_date: contract_date,
            contract_end: contract_end
        }
    });
};